package com.tmt.jpafieldvalueconvert.impl;

import com.tmt.jpafieldvalueconvert.IJpaFieldValueMonitor;
import com.tmt.jpafieldvalueconvert.MonitorLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DefaultMonitorLoader implements MonitorLoader {

    private HashMap<Class<?>, IJpaFieldValueMonitor> monitorMap = new HashMap<>();

    private List<Object> globObjects = new ArrayList<>();

    private static DefaultMonitorLoader loader = null;

    private DefaultMonitorLoader() {
    }

    public synchronized static DefaultMonitorLoader getInstance() {
        if (loader == null)
            loader = new DefaultMonitorLoader();
        return loader;
    }

    @Override
    public synchronized <T extends IJpaFieldValueMonitor> void addMonitor(Class<T> monitorClazz) {
        if (monitorMap.containsKey(monitorClazz))
            return;

        try {
            IJpaFieldValueMonitor monitor = monitorClazz.newInstance();
            monitor.setGlobObjects(globObjects);
            monitorMap.put(monitorClazz, monitor);
        } catch (Exception e) {
        }
    }

    @Override
    public <T extends IJpaFieldValueMonitor> IJpaFieldValueMonitor loadMonitor(Class<T> monitorClazz) {
        IJpaFieldValueMonitor monitor = null;
        try {
            if (!monitorMap.containsKey(monitorClazz)) {
                addMonitor(monitorClazz);
            }
            monitor = monitorMap.get(monitorClazz);
        } catch (Exception e) {
        }
        return monitor;
    }

    @Override
    public void setGlobObjects(List<Object> globObjects) {
        this.globObjects = globObjects;
    }
}
